<?php


namespace Biz\service\redPacket;

use Biz\model\redPacket\RedPacketsConfig as mRedPacketsConfig;
use Kafka\Exception;


class RedPacketsConfig
{
    /**
     * 获取当前正在进行中的红包活动
     */
    public static function getCurrentRedPacket()
    {
        $configInfo = mRedPacketsConfig::getPacketConfigInfo();
        return $configInfo;
    }

    /**
     * 获取配置列表
     * @param array $where
     * @return array
     */
    public static function getList($where = []){
        $data = $result = [];
        $data = mRedPacketsConfig::select('*', $where);

        //判断是否结束，状态改成关闭
        if(!empty($data)){
            self::updateStatus($data);
        }


        $result['list'] = $data;
        unset($where['ORDER'],$where['LIMIT']);
        $result['total'] = mRedPacketsConfig::count('id',$where);

        return $result;
    }


    public static function updateStatus($data){
        $status = false;
        $endData = [];
        $endData = array_filter($data, function($_data){
            if($_data['end_time'] < date('Y-m-d H:i:s') && $_data['status'] == mRedPacketsConfig::STATUS_NORMAL){
                return $_data;
            }
        });
        if(!empty($endData)){
            $endData = array_column($endData,'id');
            try{
                mRedPacketsConfig::update(
                    ['status' => mRedPacketsConfig::STATUS_CLOSE],
                    ['id' => $endData]
                );
                $status = true;
            }catch (Exception $e){
                $status =  false;
            }
        }
        return $status;
    }



}